import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
import { getToken, removeToken, setToken , setUser, removeUser } from "@/utils/cache/cookies"
import { resetRouter } from "@/router"
import { loginApi, getAuth } from "@/api/login"
import { type LoginRequestData } from "@/api/login/types/login"
import routeSettings from "@/config/route"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  // const username = ref<string>("")

  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()


  const login = ({ username, password }: LoginRequestData) => {
    return new Promise((resolve, reject) => {
      loginApi({ username, password }).then((res: any)=>{
        setToken(res.token)
        setUser(JSON.stringify({
          name: res.name,
          phone: res.phone,
          username: res.username,
          roleName: res.roleName,
        }))
        // username.value = res.usernam
        token.value = res.token
        resolve(token.value)
      }).catch((e)=>{
        reject(e)
      })
    });

  }

  const getInfo = async () => {
    const result:any = await getAuth()
    roles.value = result
  }
  /** 模拟角色变化 */
  const changeRoles = async (role: string) => {
    const newToken = "token-" + role
    token.value = newToken
    setToken(newToken)
    // 用刷新页面代替重新登录
    window.location.reload()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    removeUser()
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    removeUser()
    token.value = ""
    roles.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  return { token, roles, login, getInfo, changeRoles, logout, resetToken }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
